package zipfile

import (
	"archive/zip"
	"strings"
	"os"
	"errors"
	"bufio"
	"path/filepath"
	"fmt"
)

func ValidZipFile(abspath string)bool{

	basename := filepath.Base(abspath)
	if strings.HasSuffix(basename,".zip") == false{
		return false
	}

	if strings.HasPrefix(basename,".")  == true{
		return false
	}

	state,err := os.Stat(abspath)
	if err !=nil{
		return false
	}

	if state.Size() <= 0{
		return false
	}
	if state.IsDir(){
		return false
	}
	return true
}

func ReadLines(abspath string)(lines []string, err error){

	if ValidZipFile(abspath) == false{
		return nil,errors.New("non zip file.")
	}
	readClose,err := zip.OpenReader(abspath)
	defer readClose.Close()
	if err != nil{
		return nil,errors.New("open zip file error.")
	}
	//var lines []string
	for _,f :=range readClose.File{
		fo,err := f.Open()
		defer fo.Close()
		if err != nil{
			return nil,errors.New("read zip file error.")
		}
		scanner := bufio.NewScanner(fo)
		for scanner.Scan() {
			lines = append(lines, scanner.Text())
		}
		if err := scanner.Err(); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}

	}
	return lines,nil
}
